package org.vacoor.nothing.ui.sound;

import javax.sound.sampled.*;
import java.net.URL;

/**
 * 该方法使用 {@link javax.sound.sampled.AudioSystem} 播放 wav,
 * 对于包含某些编码的 wav 无法播放 (eg: Microsoft ADPCM, mp3)
 * 请使用 {@link org.vacoor.nothing.ui.sound.JMFAudioPlayer#play(java.net.URL)} 替代该方法
 * 或者转换一下, 推荐一个在线转换 http://media.io
 * <p/>
 */
public abstract class WavPlayer {

    public static void playWav(final URL url) {
        new Thread() {
            public void run() {
                AudioInputStream audioInputStream;
                try {
                    audioInputStream = AudioSystem.getAudioInputStream(url);
                } catch (Exception ignore) {
                    System.err.println(ignore);
                    return;
                }

                AudioFormat format = audioInputStream.getFormat();
                SourceDataLine auline = null;
                DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

                try {
                    auline = (SourceDataLine) AudioSystem.getLine(info);
                    auline.open(format);
                } catch (Exception ignore) {
                    System.err.println(ignore);
                    return;
                }
                auline.start();

                try {
                    int len = 0;
                    byte[] buffer = new byte[8 * 1024 * 64];

                    while (-1 != (len = audioInputStream.read(buffer))) {
                        auline.write(buffer, 0, len);
                    }
                } catch (Exception ignore) {
                    System.err.println(ignore);
                    return;
                } finally {
                    auline.drain();
                    auline.close();
                }
            }
        }.start();
    }

    private WavPlayer() {
    }
}
